package org.platform.lwc.redis.utils;


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 *redisson分布式锁工具类
 */
public class RedisFuncLock {

    @Autowired
    private RedissonClient redissonClient;

    @Transactional
    public <T> T lock(String key, int waitTime, int leaseTime, Supplier<T> success, Supplier<T> fail) throws Exception {
        RLock lock = redissonClient.getLock(key);
        boolean b = lock.tryLock(waitTime, leaseTime, TimeUnit.MILLISECONDS);
        try {
            if(b){
                return success.get();
            }else {
                return fail.get();
            }
        }finally {
            if(b){
                if(lock.isLocked()){
                    lock.unlock();
                }
            }
        }
    }
}
